<template>
  <div>
    <el-dialog
      title="出入库审批"
      v-model="visible"
      width="90%"
      draggable
      :before-close="closeDialog"
    >
      <el-table
        :data="approvalOrders"
        style="width: 100%"
        border
        highlight-current-row
        class="custom-table"
      >
        <!-- 序号列 -->
        <el-table-column type="index" width="50" label="序号" align="center" />
        <!-- 库存信息 -->
        <el-table-column label="物料信息" align="center">
          <el-table-column prop="productName" label="物料名称" width="100" />
          <el-table-column prop="brandOrStyle" label="牌号/款式" width="120">
            <template #default="{ row }">
              <span v-if="row.brandOrStyle">{{ row.brandOrStyle }}</span>
              <span v-else class="empty-placeholder">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="internalBrand" label="内部牌号" width="140">
            <template #default="{ row }">
              <span v-if="row.internalBrand">{{ row.internalBrand }}</span>
              <span v-else class="empty-placeholder">-</span>
            </template>
          </el-table-column>
          <el-table-column prop="specification" label="规格型号" width="150">
            <template #default="{ row }">
              <span v-if="row.specification">{{ row.specification }}</span>
              <span v-else class="empty-placeholder">-</span>
            </template>
          </el-table-column>
        </el-table-column>
        <!-- 发货信息 -->
        <el-table-column label="入库/出库信息" align="center">
          <el-table-column prop="operationType" label="操作类型" width="100">
            <template #default="{ row }">
              <span v-if="row.operationType === 3" :style="{ color: '#67C23A' }"
                >入库</span
              >
              <span
                v-else-if="row.operationType === 2"
                :style="{ color: '#F56C6C' }"
                >出库</span
              >
            </template>
          </el-table-column>
          <el-table-column
            v-if="materialInfo.isQuantityBased !== 2"
            prop="piece"
            :label="
              materialInfo.isQuantityBased === 0
                ? '本次发货数量'
                : '补充数量信息'
            "
            width="150"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.piece"
                :min="0"
                controls-position="right"
                :disabled="shouldDisablePiece(row)"
              >
                <template #append>件</template>
              </el-input>
            </template>
          </el-table-column>
          <!-- 重量输入列 -->
          <el-table-column
            v-if="materialInfo.isQuantityBased !== 0"
            prop="amount"
            :label="
              materialInfo.isQuantityBased === 2
                ? '本次发货重量'
                : '补充重量信息'
            "
            width="150"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.amount"
                :min="0"
                controls-position="right"
                :disabled="shouldDisableAmount(row)"
              >
                <template #append>kg</template>
              </el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 审批状态 -->
        <el-table-column label="出库/入库状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getCombinedStatusType(row)" effect="light">
              {{ getCombinedStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 时间信息 -->
        <el-table-column prop="createdAt" label="出库/入库时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-tag
                v-if="row.approvementStatus === '已审批'"
                :type="row.approveResult === '通过' ? 'success' : 'danger'"
                effect="light"
              >
                {{ row.approveResult }}
              </el-tag>
              <template v-else>
                <template
                  v-if="!row.rejectMode && row.approvementStatus === '未审批'"
                >
                  <el-button
                    type="success"
                    size="small"
                    @click="handleApprove(row)"
                  >
                    <el-icon><CircleCheck /></el-icon>确认
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="startReject(row)"
                  >
                    <el-icon><CircleClose /></el-icon>拒绝
                  </el-button>
                </template>

                <!-- 拒绝输入状态 -->
                <div v-if="row.rejectMode" class="reject-input-group">
                  <el-input
                    v-model="row.approvedComment"
                    placeholder="必须填写拒绝原因"
                    size="small"
                    clearable
                    class="reason-input"
                  />
                  <div class="reject-buttons">
                    <el-button
                      type="danger"
                      size="small"
                      :disabled="!row.approvedComment"
                      @click="handleReject(row)"
                    >
                      提交
                    </el-button>
                    <el-button size="small" @click="cancelReject(row)">
                      取消
                    </el-button>
                  </div>
                </div>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="closeDialog">
            <el-icon><Close /></el-icon> 关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { CircleCheck, CircleClose, Close } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import request from "@/utils/request";

interface ApprovalOrder {
  piece: any;
  amount: any;
  id: number;
  rejectMode?: boolean;
  approvedComment?: string;
  approvementStatus: string;
}

export default defineComponent({
  components: {
    CircleCheck,
    CircleClose,
    Close,
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
    approvalOrders: {
      type: Array as PropType<ApprovalOrder[]>,
      default: () => [],
    },
    materialInfo: {
      type: Object,
      default: () => ({}),
    },
    username: { type: String, default: "未知用户" },
  },

  setup(props, { emit }) {
    const visible = ref(props.dialogVisible);

    // 监听父组件传递的visible值变化
    watch(
      () => props.dialogVisible,
      (newVal) => {
        visible.value = newVal;
      }
    );

    console.log(props.username);

    const approvalOrders = ref<ApprovalOrder[]>([]); // 初始化为空数组

    // 新增对approvalOrders的深度监听
    watch(
      () => props.approvalOrders,
      (newVal) => {
        approvalOrders.value = newVal.map((order) => ({
          ...order,
          initialPiece: Number(order.piece),
          initialAmount: Number(order.amount),
        }));
      },
      { immediate: true, deep: true } // 立即执行+深度监听
    );

    // 件数输入禁用判断
    const shouldDisablePiece = (row: any) => {
      // 按重量计量的情况
      if (props.materialInfo.isQuantityBased === 0) return true;

      // 混合计量时的逻辑
      if (props.materialInfo.isQuantityBased === 1) {
        // 如果初始重量有值 → 永久禁用件数输入
        return Number(row.initialPiece) > 0;
      }
      return false;
    };

    // 重量输入禁用判断
    const shouldDisableAmount = (row: any) => {
      // 按件数计量的情况
      if (props.materialInfo.isQuantityBased === 2) return true;

      // 混合计量时的逻辑
      if (props.materialInfo.isQuantityBased === 1) {
        // 如果初始件数有值 → 永久禁用重量输入
        return Number(row.initialAmount) > 0;
      }
      return false;
    };
    // 日期格式化
    const formatDateTime = (datetime: string) => {
      return dayjs(datetime).format("YYYY-MM-DD HH:mm");
    };

    // 获取组合状态文本
    const getCombinedStatusText = (row: any) => {
      return row.approvementStatus === "未审批"
        ? "未审批"
        : row.approveResult || "已审批";
    };

    // 获取组合状态标签类型
    const getCombinedStatusType = (row: any) => {
      if (row.approvementStatus === "未审批") return "warning";
      return row.approveResult === "通过" ? "success" : "danger";
    };

    // 统一校验方法
    const validateQuantity = (row: any) => {
      const piece = Number(row.piece);
      const amount = Number(row.amount);

      let isValid = true;
      let message = "";

      // 核心修改：只检查 piece 和 amount 是否同时为 0 或无效
      const isPieceZeroOrInvalid = piece === 0 || isNaN(piece);
      const isAmountZeroOrInvalid = amount === 0 || isNaN(amount);

      if (isPieceZeroOrInvalid && isAmountZeroOrInvalid) {
        isValid = false;
        message = "数量和重量不能同时为零或无效值";
      }

      return { isValid, message };
    };

    // 处理确认操作
    const handleApprove = async (row: any) => {
      const { isValid, message } = validateQuantity(row);
      if (!isValid) {
        ElMessage.warning(message);
        return;
      }
      try {
        row.approvementStatus = "已审批";
        row.approvedComment = "确认，同意通过";
        row.approveResult = "通过";
        row.approvedBy = props.username;
        await submitApproval(row, true);
        //ElMessage.success("已确认通过");
      } catch (error) {
        console.error("确认操作失败:", error);
        ElMessage.error("确认操作失败");
      }
    };

    // 处理拒绝操作
    const handleReject = async (row: any) => {
      if (!row.approvedComment?.trim()) {
        ElMessage.warning("请填写拒绝原因");
        return;
      }
      try {
        row.approvementStatus = "已审批";
        row.approveResult = "拒绝";
        row.approvedBy = props.username;
        await submitApproval(row, false);
        //ElMessage.success("已提交拒绝");
      } catch (error) {
        console.error("拒绝操作失败:", error);
        ElMessage.error("拒绝操作失败");
      }
    };

    const msgToProduce = async (row: any) => {
      let result = null;
      if (row.approveResult === "通过") {
        result = 1;
      } else {
        result = 0;
      }
      const msg = {
        noteId: row.noteId,
        approved: result,
      };
      console.log(msg);
      try {
        const response = await request({
          method: "post",
          url: "/product/inventory/approval-callback",
          data: msg,
          headers: { "Content-Type": "application/json" },
        });
        if (response.data.success) {
          console.log(response);
        }
      } catch (error) {
        console.log(error);
      }
    };

    const msgToPurchase = async (row: any) => {
      let result = null;
      let description = "";
      if (row.approveResult === "通过") {
        result = 2;
        description = null;
      } else {
        result = 3;
        description = row.approvedComment;
      }
      const msg = {
        adjustmentStatus: result,
        adjustmentDescription: description,
      };
      console.log(msg);
      try {
        const response = await request({
          method: "post",
          url: `/purchase/nk?id=${row.noteId}`,
          data: msg,
          headers: { "Content-Type": "application/json" },
        });
        if (response.data.success) {
          console.log(response);
        }
      } catch (error) {
        console.log(error);
      }
    };

    const msgToSale = async (row: any) => {
      let api = "";
      if (row.approveResult === "通过") {
        api = "/sale/deliver/approveNote";
      } else {
        api = "/sale/deliver/unApproveNote";
      }
      const ApprovementUnit = {
        ...row,
      };
      try {
        const response = await request({
          method: "post",
          url: api,
          data: ApprovementUnit,
          headers: { "Content-Type": "application/json" },
        });
        if (response.data.success) {
          console.log(response);
        }
      } catch (error) {
        console.log(error);
      }
    };

    // 统一提交方法
    const submitApproval = async (row: any, approved: boolean) => {
      const payload = {
        id: row.id,
        approvedComment: row.approvedComment,
        approvedBy: row.approvedBy,
        approveResult: row.approveResult,
        actualPiece: row.piece,
        actualAmount: row.amount,
      };
      console.log(payload);

      try {
        const response = await request({
          method: "post",
          url: "/inventory/approvement/approve",
          data: payload,
          headers: { "Content-Type": "application/json" },
        });

        if (response.data.success) {
          if (approved) {
            ElMessage.success("已确认通过");
          } else {
            ElMessage.success("已提交拒绝");
          }
          emit("approval-update", {
            ...row,
            approvementStatus: approved ? "已确认" : "已拒绝",
            rejectMode: false,
          });
          if (row.department === "Produce") {
            msgToProduce(row);
          } else if (row.department === "Purchase") {
            msgToPurchase(row);
          } else if (row.department === "Sale") {
            msgToSale(row);
          }
        }
      } catch (error) {
        ElMessage.error("操作失败");
        console.log(error);
      }
    };

    // 显示拒绝输入框
    const startReject = (row: any) => {
      props.approvalOrders?.forEach((item) => {
        if (item.id !== row.id) item.rejectMode = false;
      });
      row.rejectMode = true;
      row.approvedComment = "";
    };

    // 取消拒绝操作
    const cancelReject = (row: any) => {
      row.rejectMode = false;
      row.approvedComment = "";
    };

    // 关闭对话框
    const closeDialog = () => {
      visible.value = false;
      emit("update:dialogVisible", false);
    };

    return {
      visible,
      approvalOrders,
      shouldDisablePiece,
      shouldDisableAmount,
      getCombinedStatusText,
      getCombinedStatusType,
      validateQuantity,
      handleApprove,
      handleReject,
      startReject,
      cancelReject,
      formatDateTime,
      closeDialog,
    };
  },
});
</script>

<style scoped>
.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
}

.status-text {
  color: #666;
  font-size: 0.9em;
}

.dialog-footer {
  padding: 16px 0 0;
  text-align: right;
}

:deep(.el-dialog__body) {
  padding: 15px 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  padding: 0 8px;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
}

:deep(.el-tag) {
  font-weight: 500;
  letter-spacing: 0.5px;
}
</style>